<template>
  <div class="outside">
    <!-- :isAdd="isAdd" -->
    <NavbarTen :isAdd="isAdd" v-on="{ btn_add: btn_add, btn_map: btn_map }" />
    <!-- <el-dropdown>
      <el-button size="small" type="primary">
        {{ usernamePassword.username
        }}<i class="el-icon-arrow-down el-icon--right"></i>
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item>注销</el-dropdown-item>
        <el-dropdown-item @click.native="logout()">退出</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown> -->
    <el-container id="box">
      <!-- 内容区域 -->
      <el-main>
        <div class="toptab">
          <!-- 编辑弹窗 -->
          <el-dialog
            :visible.sync="dialogOpen"
            :title="dialogText"
            width="50%"
            v-dialogDrag
            :close-on-click-modal="false"
            :before-close="cancel"
          >
            <el-tabs v-model="tenTabs" type="card" @tab-click="invalidateMap">
              <el-tab-pane label="详情" name="first">
                <!-- from表单 -->
                <el-form
                  :model="editForm"
                  :rules="editFormRules"
                  ref="editForm"
                  label-width="auto"
                  class="tabHight_auto"
                >
                  <el-form-item label="Token" prop="token">
                    <el-input
                      v-model="editForm.token"
                      :disabled="dialogText !== '添加'"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="授权标识符" prop="authenticationToken">
                    <el-input
                      v-model="editForm.authenticationToken"
                      :disabled="dialogText !== '添加'"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                  </el-form-item>
                  <el-form-item label="上传图片" prop="imageUrl">
                    <!-- <el-input v-model="editForm.imageUrl"></el-input> -->
                    <div style="display: flex">
                      <app-upload
                        :isAsycn="dialogText == '添加'"
                        :tenant2="editForm.token"
                        tips=""
                        ref="appUploadFef"
                        :is-resolution="true"
                        @subUploadSucceedAsync="subUploadSucceedAsync"
                        @subUploadSucceed="handleUploadSucceed"
                      />
                      <div class="imageHome" v-if="editForm.imageUrl != ''">
                        <img
                          style="width: 100%; height: 100%"
                          v-if="editForm.imageUrl"
                          :src="editForm.imageUrl"
                          class="image-size"
                        />
                      </div>
                    </div>
                  </el-form-item>
                  <!-- <el-form-item label="授权用户" prop="authorizedUserIds">
                    <el-select
                      v-model="users"
                      multiple
                      placeholder="请选择"
                      style="width: 80%"
                    >
                      <el-option
                        v-for="item in userList"
                        :key="item.token"
                        :label="item.username"
                        :value="item.username"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item> -->
                  <el-form-item
                    label="租户模板"
                    prop="tenantTemplateId"
                    v-if="dialogText === '添加'"
                  >
                    <el-select
                      v-model="editForm.tenantTemplateId"
                      placeholder="请选择"
                      style="width: 80%"
                    >
                      <el-option
                        v-for="item in tenantTemplates"
                        :key="item.key"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="添加" v-if="dialogText === '添加'">
                    <el-checkbox v-model="isdatasetTemplate"
                      >默认测试数据</el-checkbox
                    >
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <!-- 地图样式 -->
              <el-tab-pane label="地图" name="second">
                <div id="map"></div>
              </el-tab-pane>
            </el-tabs>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel()">取 消</el-button>
              <!-- :disabled="editForm.roleList && !editForm.roleList.includes(1)" -->
              <el-button
                :disabled="editForm.roleList && !editForm.roleList.includes(1)"
                v-if="dialogText !== '添加'"
                type="primary"
                @click="submitForm('editForm')"
                :loading="btnLoding"
                >确 定</el-button
              >
              <el-button
                :loading="btnLoding"
                v-else
                type="primary"
                @click="submitForm('editForm')"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </div>
        <div class="main_1" v-if="isMap == 'true'">
          <div id="map_main"></div>
        </div>
        <div class="main_2" v-if="isMap == 'false'">
          <div class="list-content">
            <!-- <div
              v-init-screen-h="150"
              class="nodata"
              v-if="tenantList && tenantList.length == 0"
            >
              暂无租户
            </div> -->
            <el-row
              v-init-screen-h="0"
              justify="center"
              align="bottom"
              :gutter="14"
              v-if="tenantList.length !== 0"
            >
              <el-col
                :xs="12"
                :sm="12"
                :md="8"
                :lg="6"
                :xl="6"
                v-for="(tenant, index) in tenantList"
                :key="index"
              >
                <div class="tenan_item" @click="to_home(tenant)">
                  <i class="topL"></i>
                  <i class="topR"></i>
                  <i class="bottomL"></i>
                  <i class="bottomR"></i>
                  <el-avatar
                    class="avatar_img"
                    :src="tenant.imageUrl | filtersFileUrl()"
                    style="width: 90px; height: 90px"
                  />
                  <div class="item_right">
                    <div class="ten_name">{{ tenant.name || "暂无" }}</div>
                    <div class="ten_time">
                      创建时间: {{ formatDateT(tenant.createdDate) }}
                    </div>
                    <div class="ten_set">
                      <el-tooltip content="配置" effect="light">
                        <el-button
                          class="icon_btn"
                          type="primary"
                          icon="el-icon-setting"
                          circle
                          size="mini"
                          @click.stop="handleShowConfig(tenant.token)"
                        ></el-button>
                      </el-tooltip>
                      <el-tooltip content="编辑" effect="light">
                        <el-button
                          class="icon_btn"
                          type="primary"
                          icon="el-icon-edit"
                          circle
                          size="mini"
                          @click.stop="btn_edit(tenant.token, tenant.roleList)"
                        ></el-button>
                      </el-tooltip>
                      <el-tooltip content="删除" effect="light">
                        <!-- :disabled="!tenant.roleList.includes(1)" -->
                        <div @click.stop="">
                          <el-button
                            :disabled="!tenant.roleList.includes(1)"
                            class="icon_btn"
                            type="primary"
                            icon="el-icon-remove"
                            circle
                            size="mini"
                            @click.stop="btn_remove(tenant.token)"
                          ></el-button>
                        </div>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-main>
    </el-container>
    <TenantConfigureDialog
      :dialogVisible.sync="configDialogVisible"
      :configToken="configToken"
      ref="configDialogRef"
    ></TenantConfigureDialog>
  </div>
</template>

<script>
import { NavbarTen } from "@/layout/components";
import ResizeMixin from "@/layout/mixin/ResizeHandler";
import { initMap, addControlOptions, createIcon } from "@/utils/leaflet-map";
import icon from "@/icons/comm/marker-icon-2x-violet.png";
import AppUpload from "@/views/device/devicegroups/UploadImage.vue";
import { getSourcesinkzh } from "@/api/project";
import { Loading } from "element-ui";
import EmptyData from "@/views/common/emptyData";
import { TOKEN_RULES } from "@/utils/local";
import { getTenant, postTenant, putTenant } from "@/api/tenant";
import { filtersFileUrl } from "@/filter/index";
import TenantConfigureDialog from "./components/TenantConfigureDialog";
import { CONFIG_DATA } from "./constant";
// 所有的role合并为一个集合
function flatten(arr) {
  return [].concat(...arr);
}
function deepFlatten(arr) {
  flatten = arr => [].concat(...arr);

  return flatten(arr.map(x => (Array.isArray(x) ? deepFlatten(x) : x)));
}
export default {
  components: {
    NavbarTen,
    AppUpload,
    EmptyData,
    TenantConfigureDialog
  },
  mixins: [ResizeMixin],
  computed: {
    isAdd() {
      const roleList = this.tenantList.map(item => {
        return item.roleList;
      });
      return deepFlatten(roleList).includes(1);
    },
    tenantList() {
      return this.$store.state.user.tenantList || [];
    },
    usernamePassword() {
      return this.$store.state.user.usernamePassword;
    },

    NavbarTen() {
      return this.$store.state.app.NavbarTen;
    },
    device() {
      return this.$store.state.app.device;
    },
    fixedHeader() {
      return this.$store.state.settings.fixedHeader;
    },
    sidebar() {
      return this.$store.state.app.sidebar;
    }
  },
  data() {
    return {
      configDialogVisible: false,
      btnLoding: false,
      isMap: "false",
      map: "",
      mainMap: "",
      marker: "",
      dialogOpen: false,
      dialogText: "",
      tenTabs: "first",
      // tenantList: [],
      userList: [],
      users: [],
      tenantToken: "",
      isdatasetTemplate: false,
      tenantTemplates: [
        { key: "tdenginedb", label: "涛思数据库 ", value: "tdenginedb" },
        { key: "influxdb", label: "InfluxDB", value: "influxdb" }
        // { key: "mongodb", label: "MongoDB ", value: "mongodb" },
        // { key: "iotdb", label: "IoTDB ", value: "iotdb" },
      ],
      editForm: {
        token: "",
        authenticationToken: "",
        name: "",
        imageUrl: "",
        authorizedUserIds: ["admin"],
        tenantTemplateId: "tdenginedb",
        datasetTemplateId: "empty",
        metadata: {},
        roleList: []
      },
      editFormRules: {
        token: TOKEN_RULES,
        authenticationToken: [
          { required: true, message: "请输入授权标识符", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_-]{2,30}$/,
            message: "授权标识符在2~30个字符以内,只支持字母和数字！"
          }
        ],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        imageUrl: [
          { required: true, message: "请上传图片", trigger: "blur" }
          // {
          //   pattern:
          //     /\s*(http:\/\/|https:\/\/|\/\/)\s*[\'\"\)]?([^\'\"\)]*)(jpg|jpeg|png|bmp|gif)/g,
          //   message: "请上传正确的图片链接！",
          // },
        ],
        // authorizedUserIds: [
        //   { required: true, message: "请选择授权用户", trigger: "blur" },
        // ],
        tenantTemplateId: [
          { required: true, message: "请选择租户模板", trigger: "blur" }
        ]
      },
      newFile: {},
      configToken: ""
    };
  },
  async mounted() {
    // 当前不存在zh数据去拿
    if (!localStorage.getItem("sourceSinkData")) {
      getSourcesinkzh().then(data => {
        localStorage.setItem("sourceSinkData", JSON.stringify(data.data.data));
      });
    }

    // encodeURI(
    //   "%E5%B7%B2%E7%BB%8F%E7%A7%9F%E6%88%B7%E5%AD%98%E5%9C%A8",
    //   "UTF-8"
    // );
    this.$nextTick(() => {
      document
        .querySelector("body")
        .setAttribute("style", "background-color:#EFF4FA");
    });
    // const res = await this.refreshJwt();
    this.getTenants();
  },
  methods: {
    handleShowConfig(token) {
      this.configToken = token;
      this.$store
        .dispatch("tenantConfigCommand/getTenantConfigCommand", {
          token,
          activeName: CONFIG_DATA[0].name
        })
        .then(res => {
          this.$refs.configDialogRef.activeName = CONFIG_DATA[0].name;
          this.configDialogVisible = true;
        });
    },
    // 同步上传
    handleUploadSucceed(url) {
      this.editForm.imageUrl = filtersFileUrl(url);
    },
    // 异步上传 (在提交按钮上进行上传,主要是添加的时候防止token修改)
    subUploadSucceedAsync(url, file) {
      this.editForm.imageUrl = url;
      this.newFile = file;
    },
    //刷新jwt
    refreshJwt() {
      return new Promise((resolve, reject) => {
        var component = this;
        this.$store
          .dispatch("user/refreshJwt")
          .then(() => {
            resolve("刷新成功,获取商户");
            setTimeout(function() {
              component.refreshJwt();
            }, 1000 * 60 * 5);
          })
          .catch(() => {
            console.log("刷新jwt失败");
            this.$msg("当前登陆超时,请重新登录!");
            // reject()
            this.logout();
          });
      });
    },
    async logout() {
      await this.$store.dispatch("user/logout");
      location.reload();
    },
    //时间格式化
    formatDateT(date) {
      if (date === undefined) {
        return "N/A";
      }
      return this.$moment(new Date(date)).format("YYYY-MM-DD H:mm:ss");
    },

    //新增
    btn_add() {
      console.log("this.isAdd :>> ", this.isAdd);
      if (!this.isAdd) {
        return;
      }
      this.dialogOpen = true;
      this.dialogText = "添加";
      // this.getUsers();
      this.$nextTick(() => {
        this.load_Map_2();
      });
    },
    //编辑
    btn_edit(token, roleList) {
      this.dialogOpen = true;
      this.dialogText = "编辑";
      this.tenantToken = token;
      this.getTenant(token, roleList);
      // this.getUsers();
    },
    //删除
    btn_remove(token) {
      if (this.tenantList.length == 1) {
        this.$msg({
          type: "warning",
          message: "至少要保留一个租户"
        });
        return;
      }
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        getTenant(token, "delete").then(res => {
          this.$msg({
            type: "success",
            message: "删除成功!"
          });
          this.getTenants();
        });
      });
    },
    //跳转租户项目首页
    to_home(tenant) {
      // 登录->
      // 获取拥有的租户 /tenant/list/name
      // 获取token=> /oauth/tenant
      // 获取用户信息 =>获取userid
      // 获取菜单 /menu/show
      const loadingObj = Loading.service({
        target: "outside",
        background: "rgba(0, 0, 0, 0.4)"
      });
      this.$store
        .dispatch("user/setTenant", tenant)
        .then(() => {
          // this.$store.commit("app/CLOSE_SIDEBAR", false);
          this.$store
            .dispatch("user/getAuthToken", {
              ...this.usernamePassword,
              grant_type: "password",
              // tenantId: 1,
              tenantId: tenant.tenantId
            })
            .then(res => {
              // 获取中文的 siddhi 函数

              this.$router.push("/home/dashboard");
              // location.reload();
            })
            .finally(() => {
              loadingObj.close();
            });
        })
        .finally(f => {});

      // this.$store.dispatch("user/setTenant", 15).then((res) => {
      //   // console.log("res :>> ", res);
      // });
      // return;
      // // 存储商户信息 -暂时注释
    },
    //大屏地图切换
    btn_map() {
      var that = this;
      if (that.isMap == "true") {
        that.isMap = "false";
        that.mainMap.remove();
      } else {
        that.isMap = "true";
        this.$nextTick(() => {
          that.load_Map_1();
        });
      }
    },
    // 获取用户信息
    getUsers() {
      // var that = this;
      // var param = { page: 1, pageSize: 100 };
    },
    //获取租户列表
    getTenants() {
      this.$store.dispatch("user/getTenantList", this.usernamePassword);
      // getTenantList({
      //   password: "super_admin",
      //   username: "super_admin",
      // }).then((res) => {
      //   // console.log("res :>> ", res.data.data);
      //   // this.tenantList = res.data.data;
      // });
      // return;
      // var that = this;
      // var param = { page: 1, pageSize: 100 };
    },
    //获取租户信息
    getTenant(token, roleList) {
      var that = this;
      getTenant(token).then(res => {
        const r = res.data;
        that.editForm = {
          ...r,
          imageUrl: filtersFileUrl(r.imageUrl),
          roleList
        };
        that.users = r.authorizedUserIds;
        this.$nextTick(() => {
          that.load_Map_2();
        });
      });
    },
    //确认提交
    async submitForm(formName) {
      this.editForm.authorizedUserIds = this.users;
      if (this.editForm.token == "user") {
        this.$msg('token不可设置为:"user"');
        return;
      }
      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.btnLoding = true;
          let formData = {};
          formData = Object.assign({}, this.editForm);
          formData.metadata = this.marker._latlng;
          if (this.dialogText === "添加") {
            if (this.isdatasetTemplate) {
              formData.datasetTemplateId = "construction";
            }
            const imageUrl = await this.$refs.appUploadFef.uploadFiles(
              this.newFile
            );
            postTenant({ ...formData, imageUrl, authorizedUserIds: ["admin"] })
              .then(res => {
                this.btnLoding = false;
                this.$msg({
                  type: "success",
                  message: "操作成功!"
                });
                this.dialogOpen = false;
                //清除
                this.cleardata();
                this.getTenants();
              })
              .finally(f => {
                this.btnLoding = false;
              });
          } else {
            putTenant(formData, this.tenantToken)
              .then(res => {
                this.$msg({
                  type: "success",
                  message: "操作成功!"
                });
                this.dialogOpen = false;
                //清除
                this.cleardata();
                this.getTenants();
              })
              .finally(f => {
                this.btnLoding = false;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancel() {
      this.dialogOpen = false;
      this.cleardata();
      this.isdatasetTemplate = false;
    },
    cleardata() {
      this.editForm = {
        token: "",
        authenticationToken: "",
        name: "",
        imageUrl: "",
        authorizedUserIds: ["admin"],
        tenantTemplateId: "tdenginedb",
        datasetTemplateId: "empty",
        metadata: {}
      };
      this.users = [];
      this.map.remove();
      this.marker = "";
    },
    //大屏初始化地图
    load_Map_1() {
      var latlng = "";
      var mainMap = initMap("map_main", latlng, 5);
      this.mainMap = mainMap;
      for (var value of this.tenantList) {
        if (JSON.stringify(value.metadata) != "{}") {
          let val = value;
          var myIcon = createIcon(icon);
          let marker = L.marker([val.metadata.lat, val.metadata.lng], {
            draggable: false,
            icon: myIcon
          })
            .addTo(mainMap)
            .on("click", e => {
              this.handleMapMarerClick(val, e.latlng, mainMap);
            });
        }
      }
    },
    handleMapMarerClick(item, latlng, mainMap) {
      var that = this;
      let content =
        `<div class="boundaryMask-popup">` +
        `<p class="title" id="${item.token}" style="font-size: 20px;cursor: pointer;text-align: center;font-weight: 600; color: #409EFF;">${item.name}</p>` +
        ` </div>`;
      L.popup({ minWidth: 100 })
        .setLatLng([latlng.lat, latlng.lng])
        .setContent(content)
        .openOn(mainMap);

      document.getElementById(item.token).onclick = function() {
        that.to_home(item);
      };
    },
    //编辑页初始化地图
    load_Map_2() {
      var that = this;
      var latlng = that.editForm.metadata;
      var map = initMap("map", latlng, 5);
      addControlOptions(map, ["drawMarker", "removalMode"]);

      if (this.dialogText === "编辑") {
        if (JSON.stringify(that.editForm.metadata) != "{}") {
          var lat = that.editForm.metadata.lat;
          var lng = that.editForm.metadata.lng;
          var myIcon = createIcon(icon);
          that.marker = L.marker([lat, lng], { draggable: false, icon: myIcon })
            .addTo(map)
            .bindPopup(that.editForm.name);
        }
      }
      map.on("pm:create", e => {
        if (that.marker) {
          map.removeLayer(that.marker); // 移除已有图层,限制只有一个marker
        }
        that.marker = e.marker;
      });
      map.on("pm:remove", e => {
        marker = "";
      });
      that.map = map;
    },
    //地图重新调整位置
    invalidateMap(tab) {
      if (tab.name == "second") {
        this.$nextTick(() => {
          this.map.invalidateSize(true);
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "../../assets/style/base.css";

@import "~@/styles/mixin.scss";
.imageHome {
  width: 104px;
  height: 104px;
  background: rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  border-radius: 2px;
  margin-left: 10px;
  .image-size {
    /*background: #2E2E2E;*/
    /* border-radius: 50%; */
    display: flex;
  }
}
.tenan_item {
  color: #fff;
  display: flex;
  align-items: center;
  height: 100%;
  justify-content: space-between;
  padding: 20px 10px;
  position: relative;
  margin-bottom: 20px;
  background-color: rgba(5, 19, 72, 0.86);
  border: 1px solid #1b65d0;
  box-shadow: inset 0 0 1.81818rem #07417a;
  cursor: pointer;
  .avatar_img {
    min-width: 90px;

    min-height: 90px;
    margin-right: 16px;
  }
  .item_right {
    width: 100%;
  }
  .ten_set {
    font-size: 16px;
    text-align: center;
    display: flex;
    padding: 0 20px;
    justify-content: space-between;
    .icon_btn {
      color: #fff;
      /* background-color: #1b65d0; */
      /* border-color: #1b65d0; */
      font-size: 17px;
    }
  }
  .ten_name {
    @include textoverflow(1);
    font-weight: 700;
    font-size: 20px;
    text-align: center;
  }
  .ten_time {
    font-weight: 600;
    font-size: 15px;
    border-bottom: 1px solid #3f4a61;
    border-top: 1px solid #3f4a61;
    padding: 16px 0;
    margin: 16px 0;
    text-align: center;
  }
}
html,
body {
  height: 100%;
  margin: 0;
}
body {
  /* font-family: sans-serif; */
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
.divider_1 {
  height: -webkit-fill-available;
  margin: -133px 0 0px 97px;
  width: 0px;
  background-color: #00000021;
}
html .el-main {
  min-height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 0px;
}

.outside {
  background-color: rgb(255, 255, 255);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  /deep/ .el-dialog__body {
    padding-bottom: 0;
  }
}

.el-card {
  margin: 25px 5px 0 5px;
  height: 165px;
  color: #fff;
  background-color: rgba(5, 19, 72, 0.86);
  border: 1px solid #1b65d0;
  border-radius: 0;
  box-shadow: inset 0 0 30px #07417a;
  position: relative;
}
.el-card:hover {
  /* 鼠标变小手 */
  cursor: pointer;
}

.element-icons {
  font-size: 20px;
  font-weight: 600;
  float: left;
  /* position: absolute; */
  margin-top: -91px;
  margin-left: 91%;
}
.el-pagination {
  margin-left: 32%;
  margin-top: 30px;
}
.list-content {
  /* margin: 0 25px 0 25px; */
  padding: 30px 25px 30px 25px;
  min-height: 90vh;
  .nodata {
    color: #fff;
    font-size: 20px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.outside /deep/ .el-card__body {
  padding: 0px;
  color: #c0c4cc;
  height: 100%;
}

.title-text {
  color: #ffffff;
}

.span-box {
  display: inline-block;
  position: relative;
}
.ico-pre {
  position: absolute;
  left: -21px;
  top: 12px;
}

#map {
  width: 100%;
  height: calc(50vh);
  z-index: 1;
}
#map_main {
  width: 100%;
  height: calc(90vh);
  z-index: 1;
}
.outside {
  background: url("../../assets/images/nav/t_group.png") no-repeat;
  /* background-color: #080a38; */
  background-size: cover;
  .el-main {
    background-color: inherit;
  }
}
</style>
